package ru.btabank.dom.xpath.parsers;

import ru.btabank.dom.xpath.namespace.NamespaceMap;

public class NamespaceParser extends Parser {
    NamespaceMap namespaceMap;

    public NamespaceParser() {
        super();
        this.namespaceMap = null;
    }

    public void parse(String string) throws ParsingException {
        super.parse(string);
        this.namespaceMap = mapping();
        if (lookAhead(1).getType() != Token.END_OF_EXPRESSION_TOKEN)
            throw new UnexpectedTokenException(lookAhead(1));
    }

    public NamespaceMap getNamespaceMap() {
        return this.namespaceMap;
    }

    // [1] Mapping ::= Declaration
    // | Declaration ' ' Mapping
    // [2] Declaration ::= 'xmlns:' NCName '=' StringLiteral

    private NamespaceMap mapping() throws SyntaxException {
        String declaration, prefix, URI;
        NamespaceMap namespaceMap;

        namespaceMap = new NamespaceMap();
        while (lookAhead(1).getType() == Token.IDENTIFIER_TOKEN) {
            declaration = match(Token.IDENTIFIER_TOKEN).getValue();
            if (!declaration.equals("xmlns"))
                throw new SyntaxException("Invalid namespace declaration '" + declaration
                                          + "'. Expected 'xmlns'");
            match(Token.COLON_TOKEN);
            prefix = match(Token.IDENTIFIER_TOKEN).getValue();
            match(Token.EQUALS_TOKEN);
            URI = match(Token.STRING_LITERAL_TOKEN).getValue();

            namespaceMap.add(prefix, URI);

            if (lookAhead(1).getType() == Token.WHITESPACE_TOKEN)
                match(Token.WHITESPACE_TOKEN);
        }
        return namespaceMap;
    }

}
